# -*- coding: utf-8 -*-

import xbmcplugin, xbmcgui, xbmc
import urllib, re, urllib2, string, urlparse

youtubeURL = 'plugin://plugin.video.youtube/?action=play_video&autoplay=1&videoid=%s'
rootURL = 'http://v.netstartv.com/'
youtubePlaylistURL = 'http://www.youtube.com/playlist?list='

CNTVcartoons = [[u"蕾比宝贝与哈派乐园", "PLD3XL2PHl1PiiTs_YrhaWDKfkuJqXLM86", "http://i3.ytimg.com/vi/btcr99WR4b4/mqdefault.jpg"],
[u"开心南瓜村", "PLD3XL2PHl1Piw-Uk1YYowkiGb5CqfCtJo", "http://i2.ytimg.com/vi/eVTU9tjGDvs/mqdefault.jpg"],
[u"阿诺狗与凯瑞猫", "PLD3XL2PHl1Pgc4uuIoSZml-D5OzP-bKpO", "http://i3.ytimg.com/vi/rE4Yw4xtW5o/mqdefault.jpg"],
[u"蔬果王国历险记", "PLD3XL2PHl1PjYqpk4WHpma_KequLE4wUS", "http://i2.ytimg.com/vi/UjllxMaFEf0/mqdefault.jpg"],
[u"火力少年王3", "PLD3XL2PHl1Pg37oFYjmslhv6h4Oms3K_p", "http://i4.ytimg.com/vi/Wm42NLQP7_o/mqdefault.jpg"],
[u"西游记", "PLD3XL2PHl1PjaFgvH69IqMWsvpohQVlUW", "http://i4.ytimg.com/vi/_skd3Bxjq-k/mqdefault.jpg"],
[u"大风车频道版", "PLD3XL2PHl1PhzpF7mxgIt68UAunB5eUa8", "http://i1.ytimg.com/vi/xTISCnWeWGE/mqdefault.jpg"],
[u"天工开物第一季开心岛", "PLD3XL2PHl1Ph95fG7GkL-YV_E6lNs5Fed", "http://i2.ytimg.com/vi/eV5Q_qPM8zA/mqdefault.jpg"],
[u"智力快车", "PLD3XL2PHl1PiRKNnIfweAkxkQPWjxzH50", "http://i3.ytimg.com/vi/R3sHnDLbiM0/mqdefault.jpg"],
[u"舒克和贝塔ShuKe and beta", "PLD3XL2PHl1Pjd-7kjBNXrG0O_Qm4BqHmj", "http://i3.ytimg.com/vi/Z3r3eODLcbc/mqdefault.jpg"],
[u"大头儿子和小头爸爸", "PLD3XL2PHl1PhpXSjG7NrBHTWTZ1lC8Ath", "http://i2.ytimg.com/vi/Mz0OttvCHSw/mqdefault.jpg"],
[u"喜羊羊与灰太狼之给快乐加油", "PLD3XL2PHl1PguMcUo3QcVt1F-BTD8exf_", "http://i2.ytimg.com/vi/iZQAC522mKY/mqdefault.jpg"],
[u"葫芦兄弟Calabash Brothers", "PLD3XL2PHl1PjrnsO4CMvqc79hAEk_RGZG", "http://i3.ytimg.com/vi/zu2_W4gYjmA/mqdefault.jpg"],
[u"果宝特攻", "PLD3XL2PHl1Pj0p6-7lmzeIdT1YvQBh0gc", "http://i1.ytimg.com/vi/tmu4s5JWpEE/mqdefault.jpg"],
[u"大型名著动画片 西游记", "PLD3XL2PHl1PjbwZcgcU4JU2NqANkOCssI", "http://i3.ytimg.com/vi/nIdbALLJYRo/mqdefault.jpg"],
[u"本周热门", "PL303E27E6494DBDC8", "http://i1.ytimg.com/vi/prH_MR2EkO8/mqdefault.jpg"],
[u"甜心格格", "PL506B8BF56FC3B01D", "http://i2.ytimg.com/vi/UkNlncffhQ4/mqdefault.jpg"],
[u"马拉松王子", "PL9B51B86EDB4AC330", "http://i3.ytimg.com/vi/nZASRTinJJs/mqdefault.jpg"],
[u"仓鼠乐园", "PL80198FA353C7E115", "http://i3.ytimg.com/vi/ZLYg0NgE9Mg/mqdefault.jpg"],
[u"美猴王", "PL2AAA75E88566B469", "http://i2.ytimg.com/vi/uloaXOnOxZA/mqdefault.jpg"],
[u"秦汉英雄传", "PLF5ABB5A119DBC531", "http://i1.ytimg.com/vi/HeDLL01P3C8/mqdefault.jpg"],
[u"阿凡提的故事", "PL7EE4660D2DC1F24D", "http://i2.ytimg.com/vi/aLnP62YAUS0/mqdefault.jpg"],
[u"三毛流浪记", "PL48B2A41C23B4586C", "http://i3.ytimg.com/vi/NuYSyQ2x9DE/mqdefault.jpg"],
[u"蓝巨星与绿豆鲨", "PLD46389E04052EC3A", "http://i3.ytimg.com/vi/rCe-HayuAqg/mqdefault.jpg"],
[u"宋代足球小将", "PLCB09A999AF605EE1", "http://i3.ytimg.com/vi/rlD-him-FYQ/mqdefault.jpg"],
[u"小龙人精编版", "PL6FDC820DE23D6DFA", "http://i2.ytimg.com/vi/qnBktye0ZaE/mqdefault.jpg"],
[u"虹猫蓝兔七侠传", "PLD139DE386D6390B0", "http://i1.ytimg.com/vi/PZ4iqqutVa8/mqdefault.jpg"],
[u"郑和下西洋", "PL46F2B189B2D4B974", "http://i4.ytimg.com/vi/GKhCvYwYQew/mqdefault.jpg"],
[u"秦时明月之夜尽天明", "PLEC916CEB86FB500E", "http://i4.ytimg.com/vi/WP6PZwEbaOg/mqdefault.jpg"],
[u"秦时明月之百步飞剑", "PL20FDB16DC05A4D57", "http://i1.ytimg.com/vi/LLXFFfI3avQ/mqdefault.jpg"],
[u"秦时明月之诸子百家", "PL7656CEB698978F47", "http://i3.ytimg.com/vi/NwaJHfh_-rw/mqdefault.jpg"],
[u"音乐快递", "PL66A85462974C6124", "http://i3.ytimg.com/vi/JafNM_jf5Fc/mqdefault.jpg"],
[u"宝贝一家亲", "PLB8874272CCFED166", "http://i4.ytimg.com/vi/gWs5vgWQK4E/mqdefault.jpg"],
[u"野生动物宝宝", "PLE59FAD5EB4A6BE50", "http://i1.ytimg.com/vi/x3wWh_GmFKg/mqdefault.jpg"],
[u"黑猫警长", "PL109530F3CF4C013E", "http://i1.ytimg.com/vi/H2Tg4pCFxRo/mqdefault.jpg"],
[u"宇宙星神", "PL9EEC6E87F54FBB76", "http://i2.ytimg.com/vi/-dQjBU58aBw/mqdefault.jpg"],
[u"虹猫蓝兔火凤凰", "PL3E4C5AB03EEB6A15", "http://i3.ytimg.com/vi/JLP-PjUkOjE/mqdefault.jpg"],
[u"小蝌蚪找妈妈", "PL3E9313ABE6122CD0", "http://i3.ytimg.com/vi/VHec9fytcmA/mqdefault.jpg"],
[u"阿凡提", "PLA4B7DA4E8A899F59", "http://i3.ytimg.com/vi/6_upjMMhlSI/mqdefault.jpg"],
[u"宝葫芦的秘密", "PL5A62AA5694653E9A", "http://i3.ytimg.com/vi/fENA_2ZM3j0/mqdefault.jpg"],
[u"喜羊羊与灰太狼之兔年顶呱呱", "PL39B3307D958C2922", "http://i1.ytimg.com/vi/dDL1xP1XItM/mqdefault.jpg"],
[u"大耳朵图图", "PLB9DDAA8BA08A3858", "http://i3.ytimg.com/vi/f0NpNQpbq8A/mqdefault.jpg"],
[u"动画剧场", "PL85C49D3F74850FB6", "http://i3.ytimg.com/vi/reRT9w7wckE/mqdefault.jpg"],
[u"熊出没", "PLF5A4A91339742EE6", "http://i1.ytimg.com/vi/py7KNKBRfR8/mqdefault.jpg"],
[u"哪吒传奇", "PL1FF931D29F3C5142", "http://i2.ytimg.com/vi/IuYSrGx10LU/mqdefault.jpg"],
[u"大闹天宫 The Monkey King", "PLDB3740AEF4EC2F4A", "http://i3.ytimg.com/vi/bZPIme6_FuM/mqdefault.jpg"]]

def error(message):
    addon_id=urlparse.urlsplit(sys.argv[0])[1]
    err_msg='[%s] ERROR: %s' % (addon_id, message)
    xbmcgui.Dialog().ok('错误', '不好意思，出错了！', err_msg)
    sys.exit(1)

def getPageData(url):
    user_agent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)'
    req=urllib2.Request(urllib.unquote(url))
    req.add_header('User-Agent', user_agent)
    try:
        response=urllib2.urlopen(req)
    except:
        error(url + ': URL不能打开')
    data=response.read()
    response.close()
#    items=re.compile('meta charset="(.+?)"').findall(data)
    return data

def getVideoURL(preUrl):
    videoData = getPageData(preUrl)
    videoListRex = re.compile('\[\[(.+?)]]', re.DOTALL)
    videoEleRex = re.compile('\"[-_\w]{11}\"', re.DOTALL)
    videoList = videoListRex.search(videoData)
    videlEleList = []
    if videoList:
        videoListData = videoList.group()
        videoEleList = videoEleRex.findall(videoListData)
    return videoEleList

def getCartoonVideos(plist):
    pagestr = getPageData(youtubePlaylistURL + plist)
    print pagestr
    videos = re.findall(r'href="/watch\?v=(.+)&amp;list=' + plist, pagestr)
    print videos
    shownames = re.findall(r'<span class="title video-title\s*"\s+dir="ltr">(.+)</span>', pagestr)
    print shownames
    del videos[0]
    allvideos = []
    
    for i in range(len(videos)):
        allvideos.append([shownames[i], videos[i]])
    
    return allvideos

def getMenuList(pageUrl, menuLevel):
    pageData = getPageData(pageUrl)
    menuList = [];

    rex = ['<ul(.+?)</ul>', '<li(.+?)</li>', '<a href="(.+?)">(.+?)</a>', 
    'class="movie-poster" src="(.+?)"(.+?)<h2>(.+?)<i(.+?)<a class="btn playbtn" href="(.+?)"']
    
    if menuLevel == 2:
        menuList = getVideoURL(pageUrl)
        return menuList
    else:
        m1=re.compile(rex[0], re.DOTALL).findall(pageData)
        for ul in m1:
            m2=re.compile(rex[1], re.DOTALL).findall(ul)
            for li in m2:
                if menuLevel == 0:
                    m3=re.compile(rex[2], re.DOTALL).findall(li)
                    if len(m3) > 0:
                        for href, category in m3:
                            menuList.append((category, href))
                elif menuLevel == 1:
                    m4=re.compile(rex[3], re.DOTALL).findall(li)
                    if len(m4) > 0:
                        for videoThumb, videoInfo1, videoName, videoInfo, videoHref in m4:
                            menuList.append((videoName.strip(), videoHref, videoThumb))
        return menuList

def get_params():
    param=[]
    paramstring=sys.argv[2]
    
    if len(paramstring)>=2:
        params=sys.argv[2]
        cleanedparams=params.replace('?','')
        if (params[len(params)-1]=='/'):
            params=params[0:len(params)-2]
        pairsofparams=cleanedparams.split('&')
        param={}
        for i in range(len(pairsofparams)):
            splitparams={}
            splitparams=pairsofparams[i].split('=')
            if (len(splitparams))==2:
                param[splitparams[0]]=splitparams[1]
                                
        return param

def CATEGORIES():
    menu = []
    menu = getMenuList(rootURL, 0)
    menulen = len(menu) + 1

    u = sys.argv[0] + "?url=" + urllib.quote_plus('CNTVcartoons') + "&mode=1"
    liz = xbmcgui.ListItem('【动漫频道】中国互联网电视')
    xbmcplugin.addDirectoryItem(handle, u, liz, True, menulen)
    
    for menuItem in menu:
        u = sys.argv[0] + "?url=" + urllib.quote_plus(menuItem[1]) + "&mode=1"
        liz = xbmcgui.ListItem(menuItem[0])
        xbmcplugin.addDirectoryItem(handle, u, liz, True, menulen)

def TVSHOWS(url):
    if url == 'CNTVcartoons':
        for cartoon in CNTVcartoons:
            u = sys.argv[0] + "?url=" + urllib.quote_plus(cartoon[1]) + "&mode=2" + "&showname=" + urllib.quote_plus('CNTVcartoons')
            liz = xbmcgui.ListItem(cartoon[0], thumbnailImage=cartoon[2])
            xbmcplugin.addDirectoryItem(handle, u, liz, True)        
    else:
        menu = []
        menu = getMenuList(url, 1)
        menulen = len(menu)
        
        for menuItem in menu:
            u = sys.argv[0] + "?url=" + urllib.quote_plus(menuItem[1]) + "&mode=2" + "&showname=" + urllib.quote_plus(menuItem[0])
            liz = xbmcgui.ListItem(menuItem[0], thumbnailImage=menuItem[2])
            xbmcplugin.addDirectoryItem(handle, u, liz, True, menulen)

def VIDEOLINKS(url, showname):
    if showname == 'CNTVcartoons':
        allvideos = getCartoonVideos(url)
        menulen = len(allvideos)
        for vid in allvideos:
            u = sys.argv[0] + "?url=" + urllib.quote_plus(youtubeURL % vid[1]) + "&mode=3"
            liz = xbmcgui.ListItem(vid[0])
            xbmcplugin.addDirectoryItem(handle, u, liz, False, menulen)            
    else:
        menu = []  
        menu = getMenuList(url, 2)
        menulen = len(menu)
     
        itemNumber = 1
        for menuItem in menu:
            u = sys.argv[0] + "?url=" + urllib.quote_plus(youtubeURL % menuItem[1:12]) + "&mode=3"
            name = unicode(showname, encoding = "utf-8" ) + u'第' + str(itemNumber) + u'集'
            liz = xbmcgui.ListItem(name)
            itemNumber = itemNumber + 1
            xbmcplugin.addDirectoryItem(handle, u, liz, False, menulen)    
                        

handle = int(sys.argv[1])
params = get_params()
url = None
videoid = None
showname = None
mode = 0

try:
    url = urllib.unquote_plus(params["url"])
except:
    pass
try:
    videoid = urllib.unquote_plus(params["videoid"])
except:
    pass
try:
    mode = int(params["mode"])
except:
    pass
try:
    showname = urllib.unquote_plus(params["showname"])
except:
    pass

if mode==0 or url==None or len(url)<1:
    CATEGORIES()
elif mode==1:
    TVSHOWS(url)
    xbmc.executebuiltin("Container.SetViewMode(500)")
elif mode==2:
    VIDEOLINKS(url, showname)
elif mode==3:
    xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(url)
        
xbmcplugin.endOfDirectory(handle)